package com.xiaoq.distribution.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGeneratorUtils;
import com.xiaoq.distribution.entity.DistributorEntity;
import com.xiaoq.distribution.repository.IDistributorRepository;
import com.xiaoq.vo.PagingVo;

@Repository
public class DistributorRepositoryImpl implements IDistributorRepository {
	
	@Autowired
	private Datastore datastore;

	@Override
	public DistributorEntity addDistributor(DistributorEntity distributor) {
		datastore.save(distributor);
		return distributor;
	}

	@Override
	public DistributorEntity findById(String id) {
		Query<DistributorEntity> distriQuey = datastore.find(DistributorEntity.class).field(IdGeneratorUtils.IDGENERATOR).equal(id);
		return distriQuey.get();
	}

	@Override
	public List<DistributorEntity> findByShopId(String shopId,PagingVo pvo) {
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;
		Long total = 0L;
		
		List<DistributorEntity> distributorList = new ArrayList<DistributorEntity>();
		Query<DistributorEntity> distriQuey = datastore.find(DistributorEntity.class).field("shopId").equal(shopId);
		total = distriQuey.count();
		distributorList = distriQuey.offset(pn).limit(ps).asList();
		pvo.setTc(total);
		return distributorList;
	}

	@Override
	public List<DistributorEntity> findByShopId4Agreement(String shopId) {
		List<DistributorEntity> distributorList = new ArrayList<DistributorEntity>();
		Query<DistributorEntity> distriQuey = datastore.find(DistributorEntity.class).field("shopId").equal(shopId);
		distriQuey.field("isAgree").equal(ConstantUtil.DISTRIBUTION_NOT_AGREEMENT);
		distributorList = distriQuey.asList();
		return distributorList;
	}

	@Override
	public DistributorEntity getDistributorByClientId(String clientId) {
		if(StringUtils.isBlank(clientId)){
			return null;
		}
		Query<DistributorEntity> query = datastore.find(DistributorEntity.class)
				.filter("clientId = ", clientId);

		return query.get();
	}

	@Override
	public List<DistributorEntity> getListByShopIdAndAgree(String shopId, String isAgree) {
		Query<DistributorEntity> query = datastore.find(DistributorEntity.class);
		if(StringUtils.isNotBlank(shopId)){
			query.filter("shopId", shopId);
		}
		if (StringUtils.isNotBlank(isAgree)){
			query.filter("isAgree", isAgree);
		}
		return query.asList();
	}

	@Override
	public DistributorEntity findByname(String name) {
		Query<DistributorEntity> query = datastore.find(DistributorEntity.class);
		query.filter("name", name);
		DistributorEntity distributor = query.get();
		return distributor;
	}
}
